package com.yonyou.train.yonyouec;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class SyncEcUser {
    static String appid = "bfbfdd1018ed288e";
    static String secret = "8421fbe35fc36e794e2d7e68ce67dc674372d05fbd7476de72f7748fb0b3";
    static String baseDepid = "54568";
    static String baseUrl = "https://openapi.yonyoucloud.com";
    static String tokenUrl = "/token";
    static String userUrl = "/user/dept";
    static String deptUrl = "/dept/get";
    static String userByCodeUrl = "/certified/userInfo";
    public static String token;
    public static Date time = new Date();

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    private static final Logger LOG = LoggerFactory.getLogger(SyncEcUser.class);

    private static SyncEcUser syncEcUser;

    private SyncEcUser() {
    }

    public static synchronized SyncEcUser getInstance() {
        if (syncEcUser == null) {
            syncEcUser = new SyncEcUser();
        }
        return syncEcUser;
    }

    /*
    获取ABU下所有的人员
     */
    public ArrayList<JSONObject> doGetUser() {
        ArrayList<JSONObject> users = new ArrayList<>();
        String deptUserUrl = baseUrl + userUrl;
        Map<String, String> userMap = new HashMap<>();
//        if (null == this.token || "".equals(this.token)) {
//          如果token为空，要先获取token
        this.doGetToken();
//        }
        userMap.put("access_token", token);
        ArrayList<HashMap> deptMaps = this.doGetDeptId();
        for (int i = 0; i < deptMaps.size(); i++) {
            String dept_id=(String)deptMaps.get(i).get("id");
            String url = deptUserUrl + "/" + deptMaps.get(i).get("id")+"/50";
            JSONObject userJson = this.doGet(url, userMap);
            if ("0".equals(userJson.getString("code"))) {
                JSONArray data = userJson.getJSONArray("data");
                for (int j = 0; j < data.size(); j++) {
                    JSONObject user = data.getJSONObject(j);
                    user.put("dept_name", deptMaps.get(i).get("name"));
                    users.add(user);
                }
            }
        }
        System.out.println("user info:" + users);
        LOG.info("获取到用户信息：", users);
        return users;
    }

    public JSONObject getUserByCode(String code) {
        JSONObject user = null;
        String url = baseUrl + userByCodeUrl + "/" + code;
        Map<String, String> userMap = new HashMap<>();
//        if (null == this.token || "".equals(this.token)) {
//          如果token为空，要先获取token
        this.doGetToken();
//        }
        userMap.put("access_token", token);
        JSONObject object = this.doGet(url, userMap);
        if (null != object) {
            String returnCode = object.getString("code");
            if ("0".equals(returnCode)) {
                user = object.getJSONObject("data");
                LOG.info("获取到的用户信息为：", user);
            }
        }
        return user;
    }

    /*
    获取ABU下的所有部门
     */
    public ArrayList<HashMap> doGetDeptId() {
        ArrayList<HashMap> deptMaps = new ArrayList<>();
//        depids.add(0);
        Map<String, String> deptMapReq = new HashMap<>();
        deptMapReq.put("access_token", this.token);
        deptMapReq.put("parent_id", baseDepid);
        JSONObject deptJson = this.doGet(baseUrl + deptUrl, deptMapReq);
        String code = deptJson.getString("code");
        if ("0".equals(code)) {
            JSONArray data = deptJson.getJSONArray("data");
            for (int i = 0; i < data.size(); i++) {
                HashMap<String, String> map = new HashMap();
                JSONObject dept = data.getJSONObject(i);
                map.put("id", dept.getString("id"));
                map.put("name", dept.getString("name"));
                deptMaps.add(map);
            }
        }
        LOG.info("获取到的部门id为：", deptMaps);
        return deptMaps;

    }

    /*
    获取token
     */
    public synchronized void  doGetToken() {
        if (new Date().getTime() - time.getTime() > 5400000) {
                token = null;
        }
        if (token == null || "".equals(token)) {
            Map<String, String> tokenMap = new HashMap<String, String>();
            tokenMap.put("appid", appid);
            tokenMap.put("secret", secret);
            String accessToken = "";
            JSONObject backDataObj = null;
                 backDataObj = this.doGet(baseUrl + tokenUrl, tokenMap);
            String data = backDataObj.getString("data");
            if (data == null) {
                LOG.error("获得空间访问令牌失败,请求参数appid=" + appid + ",secret=" + secret + ";返回结果=" + data);
            } else {
                accessToken = JSONObject.parseObject(data).getString("access_token");
                Integer expiresIn = JSONObject.parseObject(data).getInteger("expiresIn");
                LOG.info("已获得空间访问令牌=" + accessToken + ",有效时间是" + (expiresIn / 60 / 60) + "小时");
                time = new Date();
                token = accessToken;
            }
        }
    }


    public JSONObject doGet(String url, Map map) {
        String returnJson = null;
        try {
            returnJson = RequestUtil.doGet(url, map);
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
        } catch (ConnectException e) {
            e.printStackTrace();
        }
        return JSONObject.parseObject(returnJson);
    }

}
